package com.qixin.modules.ea.controller;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qixin.modules.ea.entity.EaBookDetail;
import com.qixin.modules.ea.mapper.EaTravelMapper;
import com.qixin.modules.ea.service.IEaBookDetailService;
import com.qixin.modules.ea.service.IEaTravelServiceCopy;
import com.qixin.modules.ea.vo.ListPageVo;
import com.qixin.modules.eaApplication.entity.EaBusinessApply;
import com.qixin.modules.eaApplication.service.IEaBusinessApplyService;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import com.qixin.modules.eaBasic.vo.IdVo;
import com.qixin.modules.rzInvoice.entity.EaBill;
import com.qixin.modules.rzInvoice.service.IEaBillService;
import com.qixin.utils.PreciseCompute;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.EmptyUtil;
import org.jeecg.common.api.vo.Result;
import com.qixin.modules.ea.entity.EaTravel;
import com.qixin.modules.ea.vo.EaTravelPage;
import com.qixin.modules.ea.service.IEaTravelService;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.mapper.ActZTaskMapper;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
* @Description: 差旅费报销单
* @Author: qixin-boot
* @Date:   2021-07-06
* @Version: V1.0
*/
@Api(tags="app差旅费报销单")
@RestController
@RequestMapping("/app/api/eaTravel")
@Slf4j
public class ApiEaTravelController {
   @Autowired
   private IEaTravelService eaTravelService;
    @Autowired
    private IEaBookDetailService eaBookDetailService;
    @Autowired
    private IEaBillService eaBillService;
    @Autowired
    private EaTaskMapper eaTaskMapper;
    @Autowired
    private IEaBusinessApplyService eaBusinessApplyService;
    @Autowired
    private INcPersonnelService ncPersonnelService;
    @Autowired
    private ActZTaskMapper actZTaskMapper;
    @Autowired
    private EaTravelMapper eaTravelMapper;

//    /**
//     * 查询差旅费报销单信息列表
//     *
//     * @param listPageVo
//     * @return Result
//     */
//    @ApiOperation(value="差旅费报销单信息列表-查询", notes="差旅费报销单信息列表-查询")
//    @PostMapping(value = "/list")
//    public Result<?> list(@RequestBody ListPageVo listPageVo) {
//        Map<String,Object> resutlList = eaTravelService.list(listPageVo);
//        return Result.OK(resutlList);
//    }

    /**
     *   添加
     *
     * @param eaTravelPage
     * @return
     */
    @AutoLog(value = "差旅费报销单-添加")
    @ApiOperation(value="差旅费报销单-添加", notes="差旅费报销单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody EaTravelPage eaTravelPage) {
        EaTravel eaTravel = new EaTravel();
        BeanUtils.copyProperties(eaTravelPage, eaTravel);

        // update-begin-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("prefix","CLBX"); // 编码前缀
        Object result = FillRuleUtil.executeRule("common_code", jsonObj);
        eaTravel.setBillNo(result.toString());
        // update-end-Autor: wjb date: 2022-02-09 10:47 for: 生成单据编号
        eaTravel.setState(0);
        eaTravelService.saveMain(eaTravel, eaTravelPage.getEaBookDetailList(),eaTravelPage.getEaApplyDetailList());
        // update-begin-author wjb 2022-02-16 15:50 for返回收款人中文
        if (StringUtils.isNotBlank(eaTravel.getRecPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaTravel.getRecPersonId());
            if(ncPersonnel != null){
                eaTravel.setRecPersonIdName(ncPersonnel.getName());
            }
        }
        // update-end-author wjb 2022-02-16 15:50 for返回收款人中文
        EaTravelPage resultPage = new EaTravelPage();
        BeanUtils.copyProperties(eaTravel,resultPage);
        resultPage.setEaBookDetailList(eaTravelPage.getEaBookDetailList());
//		resultPage.setEaApplyDetailList(eaTravelPage.getEaApplyDetailList());

        // update-begin-author wjb 2022-02-10 15:49 返回关联的申请单实体
        QueryWrapper<EaBusinessApply> params = new QueryWrapper<>();
        params.eq("ea_travel_id",eaTravel.getId());
        EaBusinessApply eaBusinessApply = eaBusinessApplyService.getOne(params);
        List<EaBusinessApply> eaBusinessApplyList = new ArrayList<>();
        eaBusinessApplyList.add(eaBusinessApply);
        resultPage.setEaApplyDetailList(eaBusinessApplyList);
        // update-end-author wjb 2022-02-10 15:49 返回关联的申请单实体

        //add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
        return Result.OK(resultPage);
    }

//
//   /**
//    *  编辑
//    *
//    * @param eaTravelPage
//    * @return
//    */
//   @AutoLog(value = "差旅费报销单-编辑")
//   @ApiOperation(value="差旅费报销单-编辑", notes="差旅费报销单-编辑")
//   @PostMapping(value = "/edit")
//   public Result<?> edit(@RequestBody EaTravelPage eaTravelPage) {
//       EaTravel eaTravel = new EaTravel();
//       BeanUtils.copyProperties(eaTravelPage, eaTravel);
//       EaTravel eaTravelEntity = eaTravelService.getById(eaTravel.getId());
//       if(eaTravelEntity==null) {
//           return Result.error("未找到对应数据");
//       }
//
//       //判断单据是否已经被提交
//       EaTravel eaTravel1 = eaTravelService.getById(eaTravelPage.getId());
//       String status = EmptyUtil.checkNull(eaTravel1.getState());   //当状态为1审批中,2已审批时,提示单据状态已变更,请刷新
//       if(status.equals("1") || status.equals("2")){
//           return Result.error("单据状态已变更,请刷新");
//       }
//
//       eaTravel.setSaveType("add");    //保存
//       Map<String,Object> returnMap = eaTravelService.updateMain(eaTravel, eaTravelPage.getEaBookDetailList(),eaTravelPage.getEaApplyDetailList(),eaTravelPage.getEaCostShareList(),eaTravelPage.getEaBorrowSubtractList());
//
//       if(returnMap.get("code").equals("-1")){
//           return Result.error(EmptyUtil.checkNull(returnMap.get("message")));
//       }else{
//           returnMap.remove("code");
//           returnMap.remove("message");
//           return Result.OK(returnMap);
//       }
//   }

    /**
     *  编辑
     *
     * @param eaTravelPage
     * @return
     */
    @AutoLog(value = "差旅费报销单-编辑")
    @ApiOperation(value="差旅费报销单-编辑", notes="差旅费报销单-编辑")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody EaTravelPage eaTravelPage) {
        EaTravel eaTravel = new EaTravel();
        BeanUtils.copyProperties(eaTravelPage, eaTravel);
        EaTravel eaTravelEntity = eaTravelService.getById(eaTravel.getId());
        if(eaTravelEntity==null) {
            return Result.error("未找到对应数据");
        }
        eaTravelService.updateMain(eaTravel, eaTravelPage.getEaBookDetailList(),eaTravelPage.getEaApplyDetailList());
        //add-begin-by 2022-02-07 wjb for 返回主表、子表数据给前端
        EaTravelPage resultPage = new EaTravelPage();
        // update-begin-author wjb 2022-02-16 15:50 for返回收款人中文
        if (StringUtils.isNotBlank(eaTravel.getRecPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaTravel.getRecPersonId());
            if(ncPersonnel != null){
                eaTravel.setRecPersonIdName(ncPersonnel.getName());
            }
        }
        // update-end-author wjb 2022-02-16 15:50 for返回收款人中文
        BeanUtils.copyProperties(eaTravel,resultPage);
        resultPage.setEaBookDetailList(eaTravelPage.getEaBookDetailList());
        // 关联的申请单实体
        QueryWrapper<EaBusinessApply> params = new QueryWrapper<>();
        params.eq("ea_travel_id",eaTravel.getId());
        EaBusinessApply eaBusinessApply = eaBusinessApplyService.getOne(params);
        List<EaBusinessApply> eaBusinessApplyList = new ArrayList<>();
        eaBusinessApplyList.add(eaBusinessApply);
        resultPage.setEaApplyDetailList(eaBusinessApplyList);
        //add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
        //add-end-by 2022-02-07 wjb for 返回主表、子表数据给前端
        return Result.OK(resultPage);
    }

//   /**
//    *   通过id删除
//    *
//    * @param idVo
//    * @return
//    */
//   @AutoLog(value = "差旅费报销单-通过id删除(未提交状态可以删除)")
//   @ApiOperation(value="差旅费报销单-通过id删除", notes="差旅费报销单-通过id删除")
//   @PostMapping(value = "/delete")
//   public Result<?> delete(@RequestBody IdVo idVo) {
//       String id = EmptyUtil.checkNull(idVo.getId());
//       EaTravel eaTravelEntity = eaTravelService.getById(id);
//       if(eaTravelEntity==null) {
//           return Result.error("未找到对应数据");
//       }
//       Map<String,Object> returnMap = eaTravelService.delMain(id);
//       if(returnMap.get("code").equals("-1")){
//           String message = EmptyUtil.checkNull(returnMap.get("message"));
//           return Result.error(message);
//       }else{
//           return Result.OK("删除成功!");
//       }
//   }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "差旅费报销单-通过id删除")
    @ApiOperation(value="差旅费报销单-通过id删除", notes="差旅费报销单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        QueryWrapper<EaTravel> params = new QueryWrapper<>();
        params.eq("id",id);
        EaTravel eaTravel = eaTravelService.getOne(params);
        if(eaTravel != null && eaTravel.getState() > 0){
            return Result.error("该单据已发起流程,不可删除!");
        }
        eaTravelService.delMain(id);
        return Result.OK("删除成功!");
    }

//    /**
//     * 通过id查询
//     *
//     * @param idVo
//     * @return
//     */
//    @ApiOperation(value="差旅费报销单-通过id查询", notes="差旅费报销单-通过id查询")
//    @PostMapping(value = "/queryById")
//    public Result<?> queryById(@RequestBody IdVo idVo) {
//        String id = EmptyUtil.checkNull(idVo.getId());
//        EaTravel eaTravel = eaTravelService.getById(id);
//        if(eaTravel==null) {
//            return Result.error("未找到对应数据");
//        }
//        Map<String, Object> resutlList = eaTravelService.selectById(id);
//        return Result.OK(resutlList);
//
//    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value="差旅费报销单-通过id查询", notes="差旅费报销单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        EaTravelPage eaTravelPage = new EaTravelPage();
        EaTravel eaTravel = eaTravelService.getById(id);
        if(eaTravel==null) {
            return Result.error("未找到对应数据");
        }
        String personIdName = "";
        // update-begin-by wjb 详情返回报销人中文、还款人中文 申请单详情 发票详情
        //查询报销人中文
        if (org.apache.commons.lang3.StringUtils.isNotBlank(eaTravel.getPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaTravel.getPersonId());
            if(ncPersonnel != null){
                personIdName = ncPersonnel.getName();
                eaTravel.setPersonIdName(personIdName);
            }
        }
        // update-begin-author wjb 2022-02-16 15:50 for返回收款人中文
        if (StringUtils.isNotBlank(eaTravel.getRecPersonId())){
            NcPersonnel ncPersonnel = ncPersonnelService.queryById(eaTravel.getRecPersonId());
            if(ncPersonnel != null){
                eaTravel.setRecPersonIdName(ncPersonnel.getName());
            }
        }
        // update-end-author wjb 2022-02-16 15:50 for返回收款人中文
        BeanUtils.copyProperties(eaTravel,eaTravelPage);
        List<EaBookDetail> eaBookDetails = eaBookDetailService.selectByMainId(eaTravel.getId());
        // 获取关联的申请单实体
        QueryWrapper<EaBusinessApply> params = new QueryWrapper<>();
        params.eq("ea_travel_id",id);
        EaBusinessApply eaBusinessApply = eaBusinessApplyService.getOne(params);
        List<EaBusinessApply> eaBusinessApplyList  = new ArrayList<>();
        eaBusinessApplyList.add(eaBusinessApply);

        eaTravelPage.setEaApplyDetailList(eaBusinessApplyList);
        eaTravelPage.setEaBookDetailList(eaBookDetails);
        //update-end-by wjb 详情返回报销人中文 申请单详情 发票详情
        return Result.OK(eaTravelPage);
    }

//    /**
//     * 差旅费报销单审批/退回
//     *
//     * @param eaTaskVo
//     * @return
//     */
//    @AutoLog(value = "差旅费报销单审批/退回")
//    @ApiOperation(value="差旅费报销单审批/退回", notes="差旅费报销单审批/退回")
//    @PostMapping(value = "/audit")
//    public Result<?> edit(@RequestBody EaTaskVo eaTaskVo) {
//        Map<String,Object> returnMap = eaTravelService.audit(eaTaskVo);
//        return Result.OK(returnMap);
//    }

//    /**
//     * 发票更新
//     *
//     * @param billIds
//     * @return
//     */
//    @AutoLog(value = "发票更新")
//    @ApiOperation(value = "发票更新", notes = "发票更新")
//    @PutMapping(value = "/updeteFpState")
//    @Transactional
//    public Result<?> updeteFpState(@RequestParam(name = "billIds", required = true) String billIds) {
//        if (!StringUtils.isEmpty(billIds)) {
//            String[] ids = billIds.split(",");
//            // 发票金额
//            double amount = 0;
//            // 实际付款金额
//            double actualEaAmt = 0;
//            // 业务表id
//            String billId = "";
//            List<EaBookDetail> eaBookDetails = new ArrayList<>();
//            List<EaBill> eaBills = new ArrayList<>();
//            for (String id : ids) {
//                // 需要更新的发票明细行数据
//                EaBookDetail eaBookDetail = eaBookDetailService.selectById(id);
//                if(eaBookDetail == null || "".equals(eaBookDetail)){
//                    return Result.error("找不到对应数据");
//                }
//                // 需要更新的发票数据
//                EaBill eaBill = eaBillService.getById(eaBookDetail.getFpid());
//                billId = eaBookDetail.getBillId();
//                // 发票被引用
//                if ("1".equals(eaBill.getIsused()) && eaBookDetail.getBillId() != null) {
//                    amount = PreciseCompute.add(amount,eaBookDetail.getAmount().doubleValue());
//                    actualEaAmt = PreciseCompute.add(actualEaAmt,eaBookDetail.getActualEaAmt().doubleValue());
//                    // 关联的表单id置为空
//                    eaBookDetail.setBillId("");
//                    // 发票状态更新
//                    eaBill.setIsused("0");
//
//                    eaBookDetails.add(eaBookDetail);
//                    eaBills.add(eaBill);
//                }
//            }
//            // 取消费用明细行和业务表单的关系
//            eaBookDetailService.updateBatchById(eaBookDetails);
//            // 修改发票已报销状态
//            eaBillService.updateBatchById(eaBills);
//
//            // 报销单减去实际付款金额、报销金额
//            if (billId != ""){
//                EaTravel eaTravel = eaTravelService.queryById(billId);
//                // 修改待办列表的还款金额
//                Map<String, Object> params = new HashMap<>();
//                params.put("form_id",billId);
//                List<EaTask> eaTasks = eaTaskMapper.selectByMap(params);
//                if(eaTasks.size() > 0){
//                    // 修改任务列表 对应的借款金额
//                    EaTask eaTask = eaTasks.get(0);
//                    eaTask.setTotalFee(new BigDecimal(PreciseCompute.sub(eaTravel.getEaAmt().doubleValue(),amount)));
//                    eaTaskMapper.updateById(eaTask);
//                }
//                // 报销金额 修改
//                eaTravel.setEaAmt(new BigDecimal(PreciseCompute.sub(eaTravel.getEaAmt().doubleValue(),amount)));
//                // 实际付款金额 修改
//                eaTravel.setActualPayAmt(new BigDecimal(PreciseCompute.sub(eaTravel.getActualPayAmt().doubleValue(),actualEaAmt)));
//                eaTravelService.updateById(eaTravel);
//            }
//        }
//        return Result.OK();
//    }

    /**
     * 发票更新
     *
     * @param billIds
     * @return
     */
    @AutoLog(value = "发票更新")
    @ApiOperation(value = "发票更新", notes = "发票更新")
    @PutMapping(value = "/updeteFpState")
    @Transactional
    public Result<?> updeteFpState(@RequestParam(name = "billIds", required = true) String billIds) {
        if (!org.apache.commons.lang.StringUtils.isEmpty(billIds)) {
            String[] ids = billIds.split(",");
            // 发票金额
            double amount = 0;
            // 实际付款金额
            double actualEaAmt = 0;
            // 业务表id
            String billId = "";
            List<EaBookDetail> eaBookDetails = new ArrayList<>();
            List<EaBill> eaBills = new ArrayList<>();
            for (String id : ids) {
                // 需要更新的发票明细行数据
                EaBookDetail eaBookDetail = eaBookDetailService.selectById(id);
                if(eaBookDetail == null || "".equals(eaBookDetail)){
                    return Result.error("找不到对应数据");
                }
                // 需要更新的发票数据
                EaBill eaBill = eaBillService.getById(eaBookDetail.getFpid());
                billId = eaBookDetail.getBillId();
                // 发票被引用
                if ("1".equals(eaBill.getIsused()) && eaBookDetail.getBillId() != null) {
                    amount = PreciseCompute.add(amount,eaBookDetail.getAmount().doubleValue());
                    actualEaAmt = PreciseCompute.add(actualEaAmt,eaBookDetail.getActualEaAmt().doubleValue());
                    // 关联的表单id置为空
                    eaBookDetail.setBillId("");
                    // 发票状态更新
                    eaBill.setIsused("0");

                    eaBookDetails.add(eaBookDetail);
                    eaBills.add(eaBill);
                }
            }
            // 取消费用明细行和业务表单的关系
            eaBookDetailService.updateBatchById(eaBookDetails);
            // 修改发票已报销状态
            eaBillService.updateBatchById(eaBills);

            // 报销单减去实际付款金额、报销金额
            if (billId != ""){
                EaTravel eaTravel = eaTravelMapper.selectById(billId);
                // 修改待办列表的还款金额
                Map<String, Object> params = new HashMap<>();
                params.put("table_id",billId);
                List<ActZTask> actZTasks = actZTaskMapper.selectByMap(params);
                if(actZTasks.size() > 0){
                    // 修改任务列表 对应的借款金额
                    ActZTask actZTask = actZTasks.get(0);
                    actZTask.setTotalFee(new BigDecimal(PreciseCompute.sub(eaTravel.getEaAmt().doubleValue(),amount)));
                    actZTaskMapper.updateById(actZTask);
                }
                // 报销金额 修改
                eaTravel.setEaAmt(new BigDecimal(PreciseCompute.sub(eaTravel.getEaAmt().doubleValue(),amount)));
                // 实际付款金额 修改
                eaTravel.setActualPayAmt(new BigDecimal(PreciseCompute.sub(eaTravel.getActualPayAmt().doubleValue(),actualEaAmt)));
                eaTravelService.updateById(eaTravel);
            }
        }
        return Result.OK();
    }

}
